<template>
    <div id="editor" v-loading.fullscreen.lock="fullscreenLoading">
        <el-row :gutter="20">
            <el-col :span="10">
                <div class="grid-content bg-purple">
                    <el-input
                        type="text"
                        placeholder="请输入标题"
                        v-model="content_title"
                        maxlength="50"
                        show-word-limit
                    >
                    </el-input>
                </div>
            </el-col>
            <el-col :span="5">
                <div class="" style="width: 90%">
                    <el-select 
                    v-model="value1" 
                    multiple 
                    default-first-option
                    filterable
                    allow-create
                    placeholder="请选择标签类型" style="width: 100%">
                        <el-option
                            v-for="item in tags_options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </div>
            </el-col>
            <el-col :span="3">
                <el-select v-model="cate_value" placeholder="请选择类型">
                    <el-option
                        v-for="item in options"
                        :key="item.value"
                        :label="item.label"
                        :value="item.value">
                    </el-option>
                </el-select>
            </el-col>
            <el-col :span="3">
                <div class="" style="text-align: right;">
                    <el-button type="primary" @click="upload_md()" id="btn">更新</el-button>
                </div>
            </el-col>
            <el-col :span="3">
                <div class="">
                    <el-button type="warning" @click="save_local_md()" id="btn1">保存为草稿</el-button>
                </div>
            </el-col>
        </el-row>
        <div id="auth_div">
            <el-switch
                style="display: block"
                v-model="auth_value2"
                active-color="#13ce66"
                inactive-color="#ff4949"
                active-text="公开"
                inactive-text="私密" @click="zhuti()">
            </el-switch>
        </div>

        <div :id="editorId">
            <textarea style="display:none;" id="init_text"></textarea>
            <textarea class="upload-textarea" name="text" id="content_area"></textarea>
        </div>    
    </div>
</template>

<script>
import $ from "jquery";
import scriptjs from 'scriptjs';
import { defaultConfig_editor, codeThemes } from '../../public/lib/editor.md';
import _global from './Global.vue'
export default {
    name: "editor",
    data() {
        return {
            fullscreenLoading: true,
            access: false,
            editor: null,
            cate_value: '',
            codeThemes,
            editorLoaded: false,
            content_text: '',
            content_title: '',
            auth_value2:true,
            tags_options: this.build_default_data(["python", "linux", "机器学习", "新奇", "前端", "杂记", "生活"]),
            options: this.build_default_data(["python","java", "php", "javascript", "linux", "other"]),
            value1: ["前端"],
        }
    },
    components: {
            // 'mavon-editor': mavonEditor
    },
    created() {},
    computed: {
        
    },

    props: {
        editorId: {
            'type': String,
            'default': 'markdown-editor',
        },
        onchange: { // 内容改变时回调，返回（html, markdown, text）
            type: Function
        },
        config: { // 编辑器配置
            type: Object
        },
        codeTheme: { // 代码高亮主题
            'type': String,
            'default': 'vibrant-ink.min.css'
        },
        initData: {
            'type': String
        },
        initDataDelay: {
            'type': Number, // 延迟初始化数据时间，单位毫秒
            'default': 0
        }
    },

    mounted(){
        var _this = this
        this.auth_check()
        setTimeout(function(){
            _this.load_md()
        }, 1000)
        setTimeout(function(){
            _this.initEditor();
        }, 2000)
    },
    watch: {
        'initData': function (newVal) {
            if(newVal) {
                this.editorLoaded && this.editor.setMarkdown(newVal);
            }
        }
    },
    methods: {
        load_md(){
            if (this.access == false){
                return
            }
            let vm = this
            let docId = localStorage.getItem('editor_aid')
            if (docId === null || docId === 'null' || docId === ""){
                this.$router.push('/404')
                return
            }
            var token = localStorage.getItem('token')
            fetch(`http://${_global.request_host}:${_global.reuqest_port}/article/detail?aid=${docId}`, {
                method:'GET',
                mode: 'cors',
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'token': token
                },
            })
            .then(resp => resp.json())
            .then(json => {
                if (json.code == 200) { // 上传成功
                    this.content_title = json.results.title
                    this.editor_name = json.results.name
                    this.editor_time = json.results.editor_time
                    let doc = {"content": json.results.message}
                    if (doc) {
                        vm.doc = doc
                        let markdownViewDiv = document.getElementById('markdown-editor')
                        if (markdownViewDiv) {
                            // markdownViewDiv.innerHTML = '<textarea style="display: none;">'
                            // vm.initView()
                            if (doc.content) {
                                document.getElementById('init_text').innerHTML = doc.content
                                vm.value1 = JSON.parse(json.results.tags)
                                vm.cate_value = json.results.cate
                            }
                        }
                    }
                }else {
                    this.$router.push('/404')
                }
            })
        },
        build_default_data(val){
            var new_datas = []
            for (var i=0; i<val.length; i++){
                var a = new Array()
                a['value']=val[i]
                a['label']=val[i]
                new_datas.push(a)
            }
            return new_datas
        },
        auth_check(){
            console.log("权限初始化")
            this.loading = true
            var token = localStorage.getItem('token')
            fetch(`http://${_global.request_host}:${_global.reuqest_port}/user/auth`, {
                method:'POST',
                headers:{
                    'Content-Type': 'application/x-www-form-urlencoded',
                    'token': token
                },
                mode: 'cors',
                body:``,
            })
            .then(resp => resp.json())
            .then(json => {
                if(json.code==200){
                    this.access = true
                    this.loading = false
                }else{
                    this.$confirm(json.results.message, '无权访问', {
                        confirmButtonText: '返回首页',
                        cancelButtonText: '去登陆',
                        type: 'warning'
                    }).then(()=> {
                        this.$router.push('dashboard')
                    }).catch(() => {
                        this.$router.push('login')
                    });
                }
            })
        },
        fetchScript: function(url) {
            return new Promise((resolve) => {
                scriptjs(url, () => {
                    resolve();
                });
            });
        },
        getConfig: function () {
            return {...defaultConfig_editor, ...this.config };
        },
        initEditor: function () {
            (async () => {
                await this.fetchScript('/lib/editor.md/jquery.js');
                await this.fetchScript('/lib/editor.md/editormd.min.js');
                $('head').append( $('<link rel="stylesheet" type="text/css" />').attr('href', '/lib/editor.md/css/editormd.min.css') );
                this.$nextTick(() => {
                    let editor = window.editormd(this.editorId, this.getConfig());
                    editor.on('load', () => {
                        setTimeout(() => { // hack bug: 一个页面多个编辑器只能初始化其中一个数据问题
                            this.editorLoaded = true;
                            this.initData && editor.setMarkdown(this.initData);
                        }, this.initDataDelay);
                    });
                    this.onchange && editor.on('change', () => {
                        let html = editor.getPreviewedHTML();
                        this.onchange({
                            markdown: editor.getMarkdown(),
                            html: html,
                            text: window.$(html).text()
                        });
                    });
                    this.editor = editor;
                    this.fullscreenLoading = false
                });
            })();
        },
        save_local_md() {
            var local_title = this.content_title
            var local_content = this.editor.getMarkdown()
            localStorage.setItem('local_title', local_title)
            localStorage.setItem('local_content', local_content)
            localStorage.setItem('local_tags', JSON.stringify(this.value1))
            this.$router.push("/");
        },
        upload_md(){
            var _this = this
            var token = localStorage.getItem('token');
            var aid = localStorage.getItem('editor_aid')
            //console.log(token);
            document.getElementById("btn").disabled=true;
            // <!--变成灰色-->
            document.getElementById('btn').style.color = "SlateGray";
            document.getElementById('btn').value = "上传中..."
            $.ajax({
                url:`http://${_global.request_host}:${_global.reuqest_port}/article/update_`,//请求的url地址
                dataType:"json",//返回格式为json
                async:true,//请求是否异步，默认为异步，这也是ajax重要特性
                headers: {
                    "Accept": "application/json; charset=utf-8",
                    "token": token
                },
                data:{"cate_value":this.cate_value, "article_title":this.content_title,"content": this.editor.getMarkdown(), "tag_value": window.JSON.stringify(this.value1), "aid": aid},//参数值
                type:"POST",//请求方式
                beforeSend:function(){
                    //请求前的处理
                },
                success:function(req){
                    //请求成功时处理
                    // 返回状态码
                    var code = req.code
                    if (code != 200){
                        alert(req.results.message)
                        // <!-- 失去效果-->
                        document.getElementById("btn").disabled=false;
                        // <!--变成灰色-->
                        document.getElementById('btn').style.color = "White";
                        document.getElementById('btn').value = "写好啦"
                        return
                    }
                    //var res = req.results;
                    // JSON -> STRING
                    // alert(req.status)
                    //<!-- 失去效果-->
                    document.getElementById("btn").disabled=false;
                    //<!--变成灰色-->
                    document.getElementById('btn').style.color = "White";
                    document.getElementById('btn').value = "写好啦"
                    // this.$router.push('/dashboard')
                    _this.$message(req.results.message + ' 3s后自动返回');
                    setTimeout(function(){
                        location.href = "/dashboard"
                    }, 3000)
                    
                },
                complete:function(){
                    //请求完成的处理
                },
                error:function(error){
                    //请求出错处理
                    alert(error);
                    //<!-- 失去效果-->
                    document.getElementById("btn").disabled=false;
                    //<!--变成灰色-->
                    document.getElementById('btn').style.color = "White";
                    document.getElementById('btn').value = "写好啦"
                }
            });
        },
    }
};
</script>
<style scoped>
#editor {
    height: 700px;
    min-width: 700px;
}

#auth_div {
    margin-bottom: 20px;
}

#markdown-editor {
    height: 700px;
}

#md_head {
    margin-bottom: 20px;
}

.el-row {
    margin-bottom: 20px;
}
.el-col {
    border-radius: 4px;
}
.bg-purple-dark {
    background: #99a9bf;
}
.bg-purple {
    background: #d3dce6;
}
.bg-purple-light {
    background: #e5e9f2;
}
.grid-content {
    border-radius: 4px;
    min-height: 36px;
}
.row-bg {
    padding: 10px 0;
    background-color: #f9fafc;
}
</style>
